package com.example.a3axismotion.utlis;

import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.example.a3axismotion.bean.Point;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class XmlUtils {

    /**
     * 单个对象生成xml
     */
    private static void XmlFileCreator(List<Point> data) {
        File newxmlfile = new File(Environment.getExternalStorageDirectory() + "/xmlparser_account.xml");
        try {
            if (!newxmlfile.exists())
                newxmlfile.createNewFile();
        } catch (IOException e) {
            Log.e("IOException", "exception in createNewFile() method");
        }
        FileOutputStream fileos = null;
        try {
            fileos = new FileOutputStream(newxmlfile);
        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", "can't create FileOutputStream");
        }
        // XmlSerializer用于写xml数据
        XmlSerializer serializer = Xml.newSerializer();
        try {
            // XmlSerializer 用 UTF-8 编码
            serializer.setOutput(fileos, "UTF-8");
            serializer.startDocument(null, Boolean.valueOf(true));
            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

            serializer.startTag(null, "accounts");
            for (Point account : data) {
            serializer.startTag(null, "point");


            serializer.startTag(null, "xValue");
            serializer.text(String.valueOf(account.getxValue()));
            serializer.endTag(null, "xValue");


            // xml-tree，由startTag开始，endTag结束
            serializer.startTag(null, "yValue");
            serializer.text(String.valueOf(account.getyValue()));
            serializer.endTag(null, "yValue");

            serializer.startTag(null, "createDate");
            serializer.text(account.getCreateDate());
            serializer.endTag(null, "createDate");

            serializer.endTag(null, "point");
            }
            serializer.endTag(null, "accounts");

            serializer.endDocument();
            // 写xml数据到FileOutputStream
            serializer.flush();
            // 关闭fileos，释放资源
            fileos.close();
        } catch (Exception e) {
            Log.e("Exception", "error occurred while creating xml file");
        }
    }
}
